package com.yixia.system.mapper.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yixia.common.utils.StringUtils;
import com.yixia.system.domain.system.SysUserPost;
import org.apache.ibatis.annotations.Mapper;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 35038
* @description 针对表【sys_user_post(用户与岗位关联表)】的数据库操作Mapper
* @createDate 2023-08-05 23:13:09
* @Entity com.yixia.entity.SysUserPost
*/
@Mapper
public interface SysUserPostMapper extends BaseMapper<SysUserPost> {


    /**
     * 根据userId添加岗位
     * @param userId
     * @param postIds
     */
    default void insertUserPost(Long userId, Long[] postIds){
        if (StringUtils.isNotNull(postIds)) {
            for (Long postId : postIds) {
                SysUserPost sysUserPost = new SysUserPost();
                sysUserPost.setPostId(postId);
                sysUserPost.setUserId(userId);
                this.insert(sysUserPost);
            }
        }
    }

    /**
     * 根据UserId修改用户岗位表
     * @param userId
     * @param postIds
     */
    default void updateUserPost(Long userId, Long[] postIds){
        /*1. 先将原来的数据进行删除*/
        LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPost::getUserId, userId);
        this.delete(queryWrapper);
        /*2. 进行新的插入*/
        insertUserPost(userId, postIds);
    }

    /**
     * 根据userIds批量删除
     * @param userIds 用户IDS
     */
    default void deleteUserPostByUserIds(Long[] userIds){
        if(userIds.length > 0){
            List<Long> collect = Arrays.stream(userIds).collect(Collectors.toList());
            LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysUserPost::getUserId, collect);
            this.delete(queryWrapper);
        }
    }

    /**
     * 根据postId来看有多少用户使用该岗位
     * @param postId 岗位ID
     * @return 结果
     */
    default int countUserPostByPostId(Long postId){
        LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPost::getPostId, postId);
        return Math.toIntExact(this.selectCount(queryWrapper));
    }
}




